package com.pactera.asmp.server.service;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.pactera.asmp.server.common.constants.ResultCode;
import com.pactera.asmp.server.common.exception.CustomException;
import com.pactera.asmp.server.dao.ConstantInfoHistoryMapper;
import com.pactera.asmp.server.pojo.ConstantInfo;
import com.pactera.asmp.server.pojo.ConstantInfoHistory;
import com.pactera.asmp.server.utils.PageDataResult;

@Service
public class ConstantInfoHistoryServiceImpl implements IConstantInfoHistoryService {

    @Autowired
    private ConstantInfoHistoryMapper constantInfoHistoryMapper;

    @Override
    public PageDataResult selective(Long constantId, Integer page, Integer limit) {
        if (null == constantId || 0 == constantId) {
            throw new CustomException(ResultCode.PARAM_IS_BLANK);
        }
        if (null == page || 0 == page.intValue()) {
            page = 1;
        }
        if (null == limit || 0 == limit.intValue()) {
            limit = 10;
        }
        if(page.intValue() < 0 || limit.intValue() < 0) {
            return new PageDataResult(0, Lists.newArrayList());
        }
        PageHelper.startPage(page, limit);
        ConstantInfoHistory constantInfoHistory = new ConstantInfoHistory();
        constantInfoHistory.setConstantId(constantId);
        List<ConstantInfoHistory> list = constantInfoHistoryMapper.select(constantInfoHistory);

        PageDataResult pageDataResult = new PageDataResult();
        PageInfo<ConstantInfoHistory> pageInfo = new PageInfo<>(list);
        pageDataResult.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
        pageDataResult.setList(list);
        return pageDataResult;
    }

    @Override
    public int insert(ConstantInfo constantInfo, Integer updateStatus) {
        ConstantInfoHistory constantInfoHistory = new ConstantInfoHistory();
        BeanUtils.copyProperties(constantInfo, constantInfoHistory);
        constantInfoHistory.setId(null);
        constantInfoHistory.setConstantId(constantInfo.getId());
        constantInfoHistory.setUpdateStatus(updateStatus);
        constantInfoHistory.setTimeCreate(LocalDateTime.now());
        return constantInfoHistoryMapper.insert(constantInfoHistory);
    }

}
